import { Directive, DirectiveBinding } from "vue";

interface ScrollLoadBinding extends DirectiveBinding {
  value: () => void;
  arg?: string; // 修改为 string 类型
}
interface ThrottleElement extends HTMLElement {
  _scrollHandler?: (...args: any[]) => void;
}
const scrollLoad: Directive = {
  mounted(el: ThrottleElement, binding: ScrollLoadBinding) {
    const { value, arg } = binding;
    let threshold = 100;

    if (arg) {
      const parsedThreshold = parseInt(arg);
      if (!isNaN(parsedThreshold)) {
        threshold = parsedThreshold;
      }
    }

    const scrollHandler = () => {
      const { scrollTop, scrollHeight, clientHeight } = el;
      if (scrollTop + clientHeight >= scrollHeight - threshold) {
        value();
      }
    };

    el._scrollHandler = scrollHandler;
    el.addEventListener("scroll", scrollHandler);
  },
  beforeUnmount(el: HTMLElement & { _scrollHandler?: () => void }) {
    if (el._scrollHandler) {
      el.removeEventListener("scroll", el._scrollHandler);
    }
  },
};

export default scrollLoad;
